package com.jxb.three;

import com.jxb.first.ListNode;

/**
 * 移除链表倒数k个元素
 *
 * @author jiaobo
 * @date Created in 2024/12/28 20:53
 **/
public class RemoveNthNode_19 {

    public static void main(String[] args) {
        ListNode head = new ListNode();
        ListNode l1 = new ListNode();
        l1.val = 2;
        ListNode l2 = new ListNode();
        l2.val = 3;
        ListNode l3 = new ListNode();
        l3.val = 4;
        ListNode l4 = new ListNode();
        l4.val = 5;
        l3.next = l4;
        l2.next = l3;
        l1.next= l2;
        head.next = l1;
        head.val = 1;
        removeNthFromEnd(head,2);
        System.out.println("...");
    }

    public static ListNode removeNthFromEnd(ListNode head, int k) {
        ListNode f = head;
        ListNode s = head;
        //先移动块指针到k个位置
        for (int i = 1;i<k+1;i++) {
            f = f.next;
        }
        //一起移动快指针和慢指针
        while (f.next != null) {
            s = s.next;
            f = f.next;
        }
        s.next = s.next.next;
        return head;
    }

}
